package Interview.toutiao;

import com.google.common.collect.Lists;

import java.util.List;

/**
 * 有序数组中找出所有等于num的下标
 * 分别找到等于num的最小下标和最大下标。则最小至最大均为找到的合适下标
 * @author leiwenkang
 * @date 2020/4/5
 */
public class Test03 {
    public static void main(String[] args) {
        Test03 test03 = new Test03();
        int[] array =  {1, 2, 3, 3, 3, 3, 4, 5, 7, 8};
        List<Integer> result = test03.findNum(array, 3);
        System.out.println(result);
    }
    public List<Integer> findNum(int[] array, int num) {
        if (array == null || array.length == 0) {
            return null;
        }

        List<Integer> result = Lists.newArrayList();
        int minIndex = getMinIndex(array, num);
        if (minIndex != - 1) {
            int maxIndex = getMaxIndex(array, num);
            for (int i = minIndex; i <= maxIndex; i++) {
                result.add(i);
            }
        }
        return result;
    }

    private int getMinIndex(int[] array, int num) {
        int start = 0;
        int end = array.length - 1;
        while (start <= end) {
            int mid = (start + end) >> 1;
            if (array[mid] == num) {
                if (mid == start || array[mid - 1] != num) {
                    return mid;
                } else {
                    end = mid - 1;
                }
            } else if (array[mid] < num) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        return -1;
    }

    private int getMaxIndex(int[] array, int num) {
        int start = 0;
        int end = array.length - 1;
        while (start <= end) {
            int mid = (start + end) >> 1;
            if (array[mid] == num) {
                if (mid == end || array[mid + 1] != num) {
                    return mid;
                } else {
                    start = mid + 1;
                }
            } else if (array[mid] < num) {
                start = mid + 1;
            } else {
                end = mid - 1;
            }
        }
        return -1;
    }
}
